package net.dopan.pigframe.oss.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.gson.Gson;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.dopan.mytools.time.DateUtil;
import net.dopan.mytools.utils.MapUtils;
import net.dopan.pigframe.core.base.controller.BaseController;
import net.dopan.pigframe.core.base.controller.response.ResponseBean;
import net.dopan.pigframe.core.utils.CommonConstant;
import net.dopan.pigframe.core.utils.Query;
import net.dopan.pigframe.core.utils.SysConfigConstant;
import net.dopan.pigframe.oss.model.entity.OSS;
import net.dopan.pigframe.oss.service.OSSConfigService;
import net.dopan.pigframe.oss.service.OSSService;
import net.dopan.pigframe.oss.storagecloud.CloudStorageConfig;
import net.dopan.pigframe.oss.storagecloud.OSSFactory;
import net.dopan.pigframe.oss.utils.ConfigConstant;
import net.dopan.pigframe.oss.utils.MimeTypeFileExtensionConvertUtils;
import net.dopan.pigframe.oss.utils.validator.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @Package: net.dopan.pigframe.oss.controller
 * @Title: OSSController
 * @Description: 文件系统上传
 * @author: 刘宽
 * @date: 2018/8/15 16:11
 */
@RestController
@RequestMapping("/api")
@Api(tags = "OSS接口(API)", description = "文件系统相关操作")
public class OSSController extends BaseController {

    @Autowired
    private OSSService ossService;

    @Autowired
    private OSSConfigService ossConfigService;

    private final static String KEY = SysConfigConstant.CLOUD_STORAGE_CONFIG_KEY;

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "列表", notes = "展示oss文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oss", value = "oss对象实体", required = true, dataType = "OSS"),
            @ApiImplicitParam(name = "params", value = "分页实体类", required = true, dataType = "Query")
    })
    public ResponseBean<Page> list(@RequestParam OSS oss, @RequestParam Map<String, Object> params) {
        params.put(CommonConstant.STATUS, CommonConstant.STATUS_NORMAL);
        if(StrUtil.isNotBlank(oss.getUrl())) {
            params.put("url", "%" + oss.getUrl() + "%");
        }
        if(StrUtil.isNotBlank(oss.getOriginalFileName())) {
            params.put("originalFileName", "%" + oss.getOriginalFileName() + "%");
        }
        if(StrUtil.isNotBlank(oss.getPlace().toString())) {
            params.put("place", oss.getPlace());
        }
        return new ResponseBean<Page>(ResponseBean.SUCCESS, "success", ossService.selectPage(new Query(params), new EntityWrapper<>()));
    }

    /**
     * 云存储配置信息
     */
    @GetMapping("/config")
    @ApiOperation(value = "云存储配置", notes = "查看配置")
    public ResponseBean<CloudStorageConfig> config(){
        CloudStorageConfig config = ossConfigService.getConfigObject(KEY, CloudStorageConfig.class);
        return new ResponseBean<>(ResponseBean.SUCCESS, "success", config);
    }

    /**
     * 保存云存储配置信息
     */
    @PutMapping("/saveConfig")
    @ApiOperation(value = "云存储配置", notes = "保存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "config", value = "CloudStorageConfig对象实体", required = true, dataType = "CloudStorageConfig")
    })
    public ResponseBean<String> saveConfig(@RequestBody CloudStorageConfig config){
        //校验类型
        ValidatorUtils.validateEntity(config);

        if(config.getType() == ConfigConstant.CloudService.FASTDFS.getValue()){
            //校验FastDFS数据
            ValidatorUtils.validateEntity(config, FastDFSGroup.class);
        }else if(config.getType() == ConfigConstant.CloudService.QINIU.getValue()){
            //校验七牛数据
            ValidatorUtils.validateEntity(config, QiniuGroup.class);
        }else if(config.getType() == ConfigConstant.CloudService.ALIYUN.getValue()){
            //校验阿里云数据
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        }else if(config.getType() == ConfigConstant.CloudService.QCLOUD.getValue()){
            //校验腾讯云数据
            ValidatorUtils.validateEntity(config, QcloudGroup.class);
        }

        ossConfigService.updateValueByKey(KEY, new Gson().toJson(config), getUserId());

        return new ResponseBean(ResponseBean.SUCCESS, "success", "");
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "上传文件", required = true, dataType = "MultipartFile")
    })
    public ResponseBean<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new ResponseBean<>(ResponseBean.SUCCESS,"file is null","");
        }
        //获取配置信息
        CloudStorageConfig config = ossConfigService.getConfigObject(KEY, CloudStorageConfig.class);
        //上传文件
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix, fileName);

        //文件描述
        Map<String, String> descriptions = new HashMap<String, String>(9);
        //0：FastDFS  1：七牛  2：阿里云  3：腾讯云
        if (0 == config.getType()) {
            descriptions.put("place", "FastDFS");
        } else if (1 == config.getType()) {
            descriptions.put("place", "七牛云");
        } else if (2 == config.getType()) {
            descriptions.put("place", "阿里云");
        } else if (3 == config.getType()) {
            descriptions.put("place", "腾讯云");
        } else {
            descriptions.put("place", "未知");
        }
        descriptions.put("filename", fileName);
        descriptions.put("mimetype", suffix.substring(1, suffix.length()));
        descriptions.put("mime", MimeTypeFileExtensionConvertUtils.getFileExtension(suffix));
        descriptions.put("filesize", String.valueOf(file.getSize() / 1000) + "K");
        descriptions.put("uploadtime", DateUtil.date());

        //保存文件信息
        OSS ossEntity = new OSS();
        ossEntity.setPlace(config.getType());
        ossEntity.setUrl(url);
        ossEntity.setOriginalFileName(fileName);
        ossEntity.setTag(MapUtils.toJson(descriptions));
        ossEntity.setCreateTime(new Date());
       // ossEntity.setCreateBy(getUserId().toString());
        ossService.insert(ossEntity);
        return new ResponseBean<>(ResponseBean.SUCCESS, "success", "https://activityplatform.oss-cn-hangzhou.aliyuncs.com"+url);
    }

    /**
     * 上传文件(多)
     */
    @PostMapping("/uploads")
    @ApiOperation(value = "上传文件(多)", notes = "上传文件(多)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "上传文件", required = true, dataType = "MultipartFile")
    })
    public ResponseBean<List<String>> uploads(@RequestPart("file") MultipartFile[] file) throws Exception {
        if(file != null && file.length > 0) {
            if(file.length <= 10) {
                List<String> urls = new ArrayList<>();
                //循环获取file数组中得文件
                for(int i = 0;i<file.length;i++) {
                    MultipartFile f = file[i];

                    //获取配置信息
                    CloudStorageConfig config = ossConfigService.getConfigObject(KEY, CloudStorageConfig.class);

                    //上传文件
                    String fileName = f.getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf("."));
                    String url = OSSFactory.build().uploadSuffix(f.getBytes(), suffix, fileName);

                    //文件描述
                    Map<String, String> descriptions = new HashMap<String, String>(9);
                    //0：FastDFS  1：七牛  2：阿里云  3：腾讯云
                    if (0 == config.getType()) {
                        descriptions.put("place", "FastDFS");
                    } else if (1 == config.getType()) {
                        descriptions.put("place", "七牛云");
                    } else if (2 == config.getType()) {
                        descriptions.put("place", "阿里云");
                    } else if (3 == config.getType()) {
                        descriptions.put("place", "腾讯云");
                    } else {
                        descriptions.put("place", "未知");
                    }
                    descriptions.put("filename", fileName);
                    descriptions.put("mimetype", suffix.substring(1, suffix.length()));
                    descriptions.put("mime", MimeTypeFileExtensionConvertUtils.getFileExtension(suffix));
                    descriptions.put("filesize", String.valueOf(f.getSize() / 1000) + "K");
                    descriptions.put("uploadtime", DateUtil.date());

                    //保存文件信息
                    OSS ossEntity = new OSS();
                    ossEntity.setPlace(config.getType());
                    ossEntity.setUrl(url);
                    ossEntity.setOriginalFileName(fileName);
                    ossEntity.setTag(MapUtils.toJson(descriptions));
                    ossEntity.setCreateTime(new Date());
                   // ossEntity.setCreateBy(getUserId().toString());
                    ossService.insert(ossEntity);

                    urls.add(url);
                }
                return new ResponseBean<>(ResponseBean.SUCCESS, "success", urls);
            }
            else {
                return new ResponseBean<>(ResponseBean.SUCCESS,"file number is over 10",new ArrayList<>());
            }
        }
        else {
            return new ResponseBean<>(ResponseBean.SUCCESS,"file is null",new ArrayList<>());
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除文件", notes = "删除文件(假删除)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "删除文件id数组", required = true, dataType = "Long")
    })
    public ResponseBean<String> delete(@RequestBody Long[] ids){
        //Long[] ids = {82861396706594816L, 82860673130434560L};
        List<Long> idss = Arrays.asList(ids);
        for(Long id : idss)
        {
            ossService.deleteByIds(id, getUserId().toString());
        }
        return new ResponseBean(ResponseBean.SUCCESS, "success", "");
    }

}
